import React, { useState, useEffect, useRef } from 'react';
import { TextField, Box, Dialog, Button, DialogTitle, DialogContent, DialogContentText, DialogActions, BottomNavigation, BottomNavigationAction, MenuItem } from '@mui/material';
import { LocalOffer as CondsIcon, Reorder as StimTargetIcon } from '@mui/icons-material';
import Utils from '../../../utils/Utils';
import NetPyNEField from '../../general/NetPyNEField';
import NetPyNETextField from '../../general/NetPyNETextField';
import NetPyNESelectField from '../../general/NetPyNESelectField';
import StimulationConditions from './StimulationConditions';

interface NetPyNEStimulationTargetProps {
  name: string;
  renameHandler?: (newName: string) => boolean;
  updates?: any;
  [key: string]: any;
}

/**
 * NetPyNEStimulationTarget Component
 * Placeholder implementation - full functionality to be migrated
 */
const NetPyNEStimulationTarget: React.FC<NetPyNEStimulationTargetProps> = ({
  name,
  renameHandler,
  updates,
  ...otherProps
}) => {
  const [currentName, setCurrentName] = useState(name);
  const [isSourceTypeNetStim, setIsSourceTypeNetStim] = useState(false);
  const [selectedIndex, setSelectedIndex] = useState(0);
  const [sectionId, setSectionId] = useState<string>('General');
  const [errorMessage, setErrorMessage] = useState<string | undefined>(undefined);
  const [errorDetails, setErrorDetails] = useState<string | undefined>(undefined);
  const renamingRef = useRef(false);
  const updateTimerRef = useRef<NodeJS.Timeout | undefined>(undefined);

  useEffect(() => {
    isStimSourceTypeNetStim();
  }, []);

  useEffect(() => {
    if (currentName !== name) {
      setCurrentName(name);
      setSelectedIndex(0);
      setSectionId('General');
    }
  }, [name]);

  useEffect(() => {
    if (updates !== undefined) {
      isStimSourceTypeNetStim();
    }
  }, [updates]);

  const isStimSourceTypeNetStim = async (stimSourceName?: string): Promise<void> => {
    let isNetStim = false;
    let stimSourceNameValue = stimSourceName;

    if (stimSourceNameValue === undefined) {
      try {
        const NETPYNE_OBJ = 'netpyne_geppetto.netParams.stimTargetParams';
        const STIM_TARGET_OBJ = `${NETPYNE_OBJ}['${name}']`;
        const SAFE_QUERY = `${STIM_TARGET_OBJ}['source'] if "${name}" in ${NETPYNE_OBJ} and "source" in ${STIM_TARGET_OBJ} else ''`;
        stimSourceNameValue = await Utils.evalPythonMessage(SAFE_QUERY, []);
      } catch (error) {
        console.log(error);
        stimSourceNameValue = '';
      }
    }

    if (stimSourceNameValue !== '') {
      isNetStim = await Utils.evalPythonMessage(
        `'NetStim' == netpyne_geppetto.netParams.stimSourceParams['${stimSourceNameValue}']['type']`,
        []
      );
    }

    if (isNetStim !== isSourceTypeNetStim) {
      setIsSourceTypeNetStim(isNetStim);
    }
  };

  const handleRenameChange = (event: React.ChangeEvent<HTMLInputElement>): void => {
    const storedValue = name;
    const newValue = Utils.nameValidation(event.target.value);
    
    if (renameHandler) {
      const updateCondition = renameHandler(newValue);
      const triggerCondition = Utils.handleUpdate(
        updateCondition,
        newValue,
        event.target.value,
        { 
          setState: (updater: any) => {
            if (typeof updater === 'function') {
              // Handle function updater if needed
            } else {
              setErrorMessage(updater.errorMessage);
              setErrorDetails(updater.errorDetails);
            }
          }
        },
        'StimulationTarget'
      );

      if (triggerCondition) {
        triggerUpdate(() => {
          Utils.renameKey(
            'netParams.stimTargetParams',
            storedValue,
            newValue,
            (response: any, newVal: string) => {
              renamingRef.current = false;
            }
          );
          renamingRef.current = true;
        });
      }
    }
  };

  const triggerUpdate = (updateMethod: () => void): void => {
    if (updateTimerRef.current !== undefined) {
      clearTimeout(updateTimerRef.current);
    }
    updateTimerRef.current = setTimeout(updateMethod, 1000);
  };

  const handleSelection = (selection: string): void => {
    Utils.evalPythonMessage(
      `'NetStim' == netpyne_geppetto.netParams.stimSourceParams['${selection}']['type']`,
      []
    ).then((response: boolean) => {
      setIsSourceTypeNetStim(response);
    });
  };

  const select = (index: number, sectionIdValue: string): void => {
    setSelectedIndex(index);
    setSectionId(sectionIdValue);
  };

  const dialogPop = errorMessage !== undefined ? (
    <Dialog open style={{ whiteSpace: 'pre-wrap' }}>
      <DialogTitle>{errorMessage}</DialogTitle>
      <DialogContent style={{ overflow: 'auto' }}>
        <DialogContentText>{errorDetails}</DialogContentText>
      </DialogContent>
      <DialogActions>
        <Button
          variant="contained"
          color="primary"
          onClick={() => {
            setErrorMessage(undefined);
            setErrorDetails(undefined);
          }}
        >
          BACK
        </Button>
      </DialogActions>
    </Dialog>
  ) : null;

  let content: React.ReactNode = null;

  const postProcessMenuItems = (pythonData: string[], selectedStimSourceName: string | string[]): React.ReactNode[] => {
    const selectedName = Array.isArray(selectedStimSourceName) ? selectedStimSourceName[0] : selectedStimSourceName;
    if (selectedName && typeof selectedName === 'string' && selectedName !== '' && selectedName !== 'object') {
      isStimSourceTypeNetStim(selectedName);
    }
    return pythonData.map((name) => (
      <MenuItem id={`${name}MenuItem`} key={name} value={name}>
        {name}
      </MenuItem>
    ));
  };

  const postProcessMenuItems4SynMech = (pythonData: string[]): React.ReactNode[] => {
    return pythonData.map((name) => (
      <MenuItem id={`${name}MenuItem`} key={name} value={name}>
        {name}
      </MenuItem>
    ));
  };

  if (sectionId === 'General') {
    const generalContent = (
      <>
        <NetPyNEField id="netParams.stimTargetParams.source">
          <NetPyNESelectField
            fullWidth
            model={`netParams.stimTargetParams['${name}']['source']`}
            method="netpyne_geppetto.getAvailableStimSources"
            postProcessItems={postProcessMenuItems}
          />
        </NetPyNEField>

        <NetPyNEField id="netParams.stimTargetParams.sec">
          <NetPyNETextField
            fullWidth
            variant="filled"
            model={`netParams.stimTargetParams['${name}']['sec']`}
          />
        </NetPyNEField>

        <NetPyNEField id="netParams.stimTargetParams.loc">
          <NetPyNETextField
            fullWidth
            variant="filled"
            model={`netParams.stimTargetParams['${name}']['loc']`}
          />
        </NetPyNEField>
      </>
    );

    const extraContent = isSourceTypeNetStim ? (
      <>
        <NetPyNEField id="netParams.stimTargetParams.synMech">
          <NetPyNESelectField
            fullWidth
            model={`netParams.stimTargetParams['${name}']['synMech']`}
            method="netpyne_geppetto.getAvailableSynMech"
            postProcessItems={postProcessMenuItems4SynMech}
          />
        </NetPyNEField>

        <NetPyNEField id="netParams.stimTargetParams.weight">
          <NetPyNETextField
            fullWidth
            variant="filled"
            model={`netParams.stimTargetParams['${name}']['weight']`}
          />
        </NetPyNEField>

        <NetPyNEField id="netParams.stimTargetParams.delay">
          <NetPyNETextField
            fullWidth
            variant="filled"
            model={`netParams.stimTargetParams['${name}']['delay']`}
          />
        </NetPyNEField>

        <NetPyNEField id="netParams.stimTargetParams.synsPerConn">
          <NetPyNETextField
            fullWidth
            variant="filled"
            model={`netParams.stimTargetParams['${name}']['synsPerConn']`}
          />
        </NetPyNEField>
      </>
    ) : null;

    content = (
      <Box className="scrollbar scrollchild" mt={1}>
        {generalContent}
        {extraContent}
      </Box>
    );
  } else if (sectionId === 'Conditions') {
    content = <StimulationConditions name={currentName} />;
  }

  return (
    <div className="layoutVerticalFitInner">
      <BottomNavigation
        showLabels
        sx={{ borderRadius: '4px' }}
        value={selectedIndex}
      >
        <BottomNavigationAction
          id="stimTargetGeneralTab"
          key="General"
          label="General"
          icon={<StimTargetIcon />}
          onClick={() => select(0, 'General')}
        />
        <BottomNavigationAction
          id="stimTargetCondsTab"
          key="Conditions"
          label="Conditions"
          icon={<CondsIcon />}
          onClick={() => select(1, 'Conditions')}
        />
      </BottomNavigation>
      <Box className="scrollbar scrollchild" mt={1}>
        {sectionId === 'General' && (
          <Box mb={1}>
            <TextField
              fullWidth
              variant="filled"
              onChange={handleRenameChange}
              value={currentName}
              disabled={renamingRef.current}
              label="The name of the stimulation target"
            />
          </Box>
        )}
        {content}
      </Box>
      {dialogPop}
    </div>
  );
};

export default NetPyNEStimulationTarget;

